/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:38917
 * Date:2025/4/22
 * Time:19:44
 */
class ListNode {
    public static class Node{
        int val;
        Node next;
        public Node(int val){
            this.val = val;
        }
        @Override
        public String toString() {
            return "Node{" +
                    "val=" + val +
                    '}';
        }
    }
    //
    public Node createList(){
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        node1.next = node2;
        /*node2.next = node3;
        node3.next = node4;
        node4.next = node5;*/
        return node1;
    }
}
public class Solution {
    private static final ListNode.Node head = new ListNode().createList();
    public static ListNode.Node removeNthFromEnd(ListNode.Node head, int n) {
        if(head == null || head.next == null) {
            return null;
        }
        ListNode.Node temp = head;
        int count = 0;
        while(temp != null) {
            count++;
            temp = temp.next;
        }
        //判断是不是头删
        if(count == n) {
            return head.next;
        }
        ListNode.Node fast = head;
        for(int i = 0; i < n; i++){
            fast = fast.next;
        }
        ListNode.Node slow = head;
        //找到要删除节点的前一个节点
        while(fast != null && fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
        ListNode.Node cur = slow.next;
        slow.next = cur.next;
        cur.next = null;
        return head;
    }
    public static void main(String[] args) {
        ListNode.Node ret = removeNthFromEnd(head, 1);
        while (ret != null) {
            System.out.println(ret);
            ret = ret.next;
        }
    }
}
